package org.example.ag_notes.repository;
import jakarta.transaction.Transactional;
import org.example.ag_notes.entity.Article;
import org.example.ag_notes.entity.Tag;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.Set;

@Repository
public interface ArticleRepository extends CrudRepository<Article, Integer> {

    // 1. 按文章ID查找（CrudRepository已内置）

    // 2. 按用户ID查找所有文章
    List<Article> findByAuthorId(Integer userId);

    // 3. 按标签查找文章
    List<Article> findByTag(String tag);

    // 4. 按用户ID和标签联合查询
    List<Article> findByAuthorIdAndTag(Integer userId, String tag);

    // 5. 检查指定用户是否有某标题的文章
    boolean existsByAuthorIdAndTitle(Integer userId, String title);

    // 新增的JOIN FETCH方法
    @Query("SELECT DISTINCT a FROM Article a LEFT JOIN FETCH a.tags WHERE a.id = :id")
    Optional<Article> findByIdWithTags(@Param("id") Integer id);

    //获取标签
    @Query("SELECT DISTINCT t FROM Article a JOIN a.tags t WHERE a.id = :articleId")
    Set<Tag> findTagsByArticleId(@Param("articleId") Integer articleId);

}